const webpack = require('webpack');
const HappyPack = require('happypack');
const happyThreadPool = HappyPack.ThreadPool({ size: 5 });
const fs = require('fs');
const _ = require('lodash');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const cfg = require('./config');

const isDev = process.env.NODE_ENV !== 'production';

exports.entry = {
    bundle: cfg.src.web.entry,
    vendor: cfg.src.web.libs
};

let common = {
    name: 'vendor'
};
if (cfg.core) {
    exports.entry.core = ['core-js'];
    common = {
        names: ['vendor', 'core']
    };
}

function babelLoader(dir, env) {
    const babelrc = fs.readFileSync(`${dir}/.babelrc`);
    let babelrcObject = {};

    try {
        babelrcObject = JSON.parse(babelrc);
    } catch (err) {
        console.error('==>     ERROR: Error parsing your .babelrc.');
        console.error(err);
    }

    const babelrcEnvObject = babelrcObject.env[env];
    let babelLoaderQuery = _.extend({}, babelrcObject, {cacheDirectory: true});
    let combinedPlugins = babelrcObject.plugins || [];
    if (babelrcEnvObject) {
        combinedPlugins = combinedPlugins.concat(babelrcEnvObject.plugins);
        babelLoaderQuery = _.extend({}, babelLoaderQuery, babelrcEnvObject, {plugins: combinedPlugins});
    }

    return ['babel', JSON.stringify(babelLoaderQuery)].join('?');
}
const jsLoader = {
    test: /\.js$/,
    exclude: /node_modules/,
    loaders: ['happypack/loader?id=js'],
    include: cfg.src.web.path
};

const plugins = [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.CommonsChunkPlugin(common),
    ...cfg.plugins,
    new webpack.ProvidePlugin({
        fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch'
    }),
    new HtmlWebpackPlugin({
        template: `!!handlebars!${cfg.src.web.dir}/index.html`,
        minify: isDev ? false : {collapseWhitespace: true},
        jses: isDev ? cfg.libs.jses : [],
        csses: isDev ? cfg.libs.csses : [],
    }),
    new ExtractTextPlugin(`default${isDev ? '' : '.[hash]'}.css`)
];

const hppyLoaders = {
    js: babelLoader(cfg.src.web.path, process.env.NODE_ENV),
    //css: isDev ? 'css?sourceMap' : 'css',
    //less: isDev ? 'css?sourceMap!less?sourceMap' : 'css!less',
    /*font: `file?name=font/[name]${isDev ? '' : '.[hash]'}.[ext]`,
    img: `url?prefix=img/&limit=10000`,*/
    favicon: 'file?name=[name].[ext]',
    html: 'html'
};

for (const k in hppyLoaders) {
    plugins.push(new HappyPack({
        loaders: [hppyLoaders[k]],
        id: k,
        threadPool: happyThreadPool,
        tempDir: `${cfg.tmp.dir}/.cache/`,
        cachePath: `${cfg.tmp.dir}/.cache/cache--[id].json`,
    }));
}

exports.plugins = plugins;

exports.loaders = {
    preLoaders: [{
        test: /\.js$/,
        loader: 'eslint',
        exclude: /node_modules/
    }],
    loaders: [
        jsLoader, {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract('style', isDev ? 'css?sourceMap' : 'css')
        }, {
            test: /\.less$/,
            loader: ExtractTextPlugin.extract('style', isDev ? 'css?sourceMap!less?sourceMap' : 'css!less')
        }, {
            test: /\.(eot|woff[2]?|ttf|svg)([?]?.*)$/,
            loader: `file?name=font/[name]${isDev ? '' : '.[hash]'}.[ext]`
        }, {
            test: /\.(png|jpe?g|gif)$/,
            loader: 'url?prefix=img/&limit=10000'
        }, {
            test: /favicon.ico/,
            loader: 'happypack/loader?id=favicon'
        }, {
            test: /\.html$/,
            loader: "happypack/loader?id=html"
        }]
};
